"use client"
import React, {useState, useEffect, useRef} from 'react';
import {observer} from 'mobx-react-lite';
import {
    Table,
    Button,
    Input,
    Tooltip,
    TableHeader,
    TableColumn,
    TableBody,
    TableRow,
    TableCell,
    getKeyValue,
    Modal,
    ModalContent,
    ModalHeader,
    ModalBody,
    ModalFooter,
    Form as FormA,
    Card,
    Pagination,
} from "@nextui-org/react";
import {message} from 'antd';
import Form from 'next/form';
import {EyeIcon, EditIcon, DeleteIcon} from '../../assets/svgs/icons'
import store from '../../models/example';
import {fetch} from '../../utils/request';
// import '../../styles/example.less';
// import './index.module.less';

const Example = observer((props) => {
    console.log('PROPSEXAMPLE', props);
    console.log('Form', Form);
    console.log('FormA', FormA);
    console.log('STORE', store);
    const formRef = useRef();
    console.log('formRef', formRef);
    const [messageApi, contextHolder] = message.useMessage();
    const [isOpen, setOpen] = useState(false);
    const [currentTarget, setCurrent] = useState({});
    const [searchParams, setSearchParams] = useState({
        name: '',
        from: '',
        to: '',
        minPrice: '',
        maxPrice: '',
        number: ''
    });
    const [isAddModalOpen, setAddModalOpen] = useState(false);
    const [newItem, setNewItem] = useState({
        name: '',
        from: '',
        to: '',
        price: '',
        number: ''
    });
    const [page, setPage] = useState(1);
    // const [rowsPerPage, setRowsPerPage] = useState(10);
    const rowsPerPage = 10;
    // const [total, setTotal] = useState(0);
    // const renderCell = useCallback((user, columnKey) => {
    //     const cellValue = user[columnKey];
    // });
    const success = () => {
        console.log('成功')
        messageApi.open({
            type: 'success',
            content: 'This is a success message',
        });
    };
    useEffect(() => {
        store.getFoods({
            pageNum: page,
            pageSize: rowsPerPage,
            ...searchParams
        });
    }, [page, rowsPerPage]);
    const columns = [
        {
            key: "id",
            label: "ID",
        },
        {
            key: "name",
            label: "名称",
        },
        {
            key: "price",
            label: "价格",
        },
        {
            key: "number",
            label: "数量",
        },
        {
            key: 'from',
            label: '出发地'
        },
        {
            key: 'to',
            label: '目的地'
        },
        {
            key: "actions",
            label: "操作"
        },
    ];
    const onSubmit = (e) => {
        e.preventDefault();
        const data = Object.fromEntries(new FormData(e.currentTarget));
        console.log('form提交', data);
        fetch('api3/users/editFood', {
            method: 'POST',
            data: {
                ...data,
                id: currentTarget?.id
            }
        }).then((res) => {
            console.log('编辑回调', res);
            if(res && res.errCode === 0){
                messageApi.open({
                    type: 'success',
                    content: '修改成功',
                });
                store.getFoods();
                setCurrent({});
                setOpen(false)
            }
        })
        // setSubmitted(data);
    };
    const handleSearch = (e) => {
        e.preventDefault();
        const formData = Object.fromEntries(new FormData(e.currentTarget));
        console.log('搜索参数:', formData);

        const searchData = {
            ...formData,
            pageNum: 1,
            pageSize: rowsPerPage,
            minPrice: formData.minPrice ? parseInt(formData.minPrice) : undefined,
            maxPrice: formData.maxPrice ? parseInt(formData.maxPrice) : undefined
        };

        if (!searchData.minPrice) delete searchData.minPrice;
        if (!searchData.maxPrice) delete searchData.maxPrice;

        setPage(1);
        store.getFoods(searchData);
    };
    const handleAddSubmit = (e) => {
        e.preventDefault();
        const formData = Object.fromEntries(new FormData(e.currentTarget));
        console.log('formData', formData);
        fetch('api3/users/addFood', {
            method: 'POST',
            data: {
                ...formData,
                price: parseInt(formData.price)
            }
        }).then((res) => {
            if(res && res.errCode === 0) {
                messageApi.open({
                    type: 'success',
                    content: '添加成功',
                });
                store.getFoods();
                setAddModalOpen(false);
                setNewItem({name: '', from: '', to: '', price: '', number: ''});
            }
        });
    };
    return (
        <div>
            {contextHolder}
            <Card className="mb-5">
                <FormA onSubmit={handleSearch} className="p-4">
                    <div className="flex flex-wrap lg:flex-wrap gap-2 justify-start">
                        <div className="w-[350px]">
                            <Input
                                label="名称"
                                name="name"
                                value={searchParams.name}
                                onChange={(e) => setSearchParams({...searchParams, name: e.target.value})}
                                className="w-full"
                                size="sm"
                            />
                        </div>
                        <div className="w-[350px]">
                            <Input
                                label="出发地"
                                name="from"
                                value={searchParams.from}
                                onChange={(e) => setSearchParams({...searchParams, from: e.target.value})}
                                className="w-full"
                                size="sm"
                            />
                        </div>
                        <div className="w-[350px]">
                            <Input
                                label="目的地"
                                name="to"
                                value={searchParams.to}
                                onChange={(e) => setSearchParams({...searchParams, to: e.target.value})}
                                className="w-full"
                                size="sm"
                            />
                        </div>
                        <div className="w-[350px]">
                            <div className="flex gap-2">
                                <Input
                                    label="最小价格"
                                    name="minPrice"
                                    type="number"
                                    value={searchParams.minPrice}
                                    onChange={(e) => setSearchParams({...searchParams, minPrice: e.target.value})}
                                    className="w-full"
                                    size="sm"
                                />
                                <div className="self-end mb-2">-</div>
                                <Input
                                    label="最大价格"
                                    name="maxPrice"
                                    type="number"
                                    value={searchParams.maxPrice}
                                    onChange={(e) => setSearchParams({...searchParams, maxPrice: e.target.value})}
                                    className="w-full"
                                    size="sm"
                                />
                            </div>
                        </div>
                        <div className="w-[350px]">
                            <Input
                                label="数量"
                                name="number"
                                type="number"
                                value={searchParams.number}
                                onChange={(e) => setSearchParams({...searchParams, number: e.target.value})}
                                className="w-full"
                                size="sm"
                            />
                        </div>
                        <div className="flex gap-2 self-end">
                            <Button className="flex-1 lg:flex-initial" color="primary" type="submit" size="sm">
                                搜索
                            </Button>
                            <Button
                                className="flex-1 lg:flex-initial"
                                variant="flat"
                                onPress={() => {
                                    setSearchParams({
                                        name: '',
                                        from: '',
                                        to: '',
                                        minPrice: '',
                                        maxPrice: '',
                                        number: ''
                                    });
                                    setPage(1);
                                    store.getFoods({ pageNum: 1, pageSize: rowsPerPage });
                                }}
                                size="sm"
                            >
                                重置
                            </Button>
                        </div>
                    </div>
                </FormA>
            </Card>
            <div className="flex justify-end gap-2 mb-4">
                <Button onClick={() => store.addFood()}>  Count: {store.count}</Button>
                <Button onClick={() => store.increment()}>Increment</Button>
                <Button onClick={() => store.decrement()}>Decrement</Button>
                <Button onClick={() => success()}>Success</Button>
                <Button
                    onClick={() => setAddModalOpen(true)}
                    color="primary"
                >
                    添加物品
                </Button>
            </div>
            <Table
                aria-label="Example table with dynamic content"
                bottomContent={
                    <div className="flex w-full justify-end items-center px-2 py-2">
                        <div className="text-small text-default-400">
                            共 {store.total} 条记录
                        </div>
                        &nbsp;&nbsp;
                        <Pagination
                            isCompact
                            showControls
                            showShadow
                            color="primary"
                            // defaultPage={1}
                            page={page}
                            total={Math.max(1, Math.ceil(store.total / rowsPerPage))}
                            onChange={(newPage) => setPage(newPage)}
                            classNames={{
                                wrapper: "gap-0 overflow-visible h-8",
                                item: "w-8 h-8",
                                cursor: "bg-primary text-white font-bold"
                            }}
                        />
                    </div>
                }
            >
                <TableHeader columns={columns}>
                    {(column) => <TableColumn key={column.key || ''} align='center'>{column.label}</TableColumn>}
                </TableHeader>
                <TableBody items={store.mockFoods}>
                    {(item) => (
                        <TableRow key={item.id || item.key || ''}>
                            {(columnKey) =>
                                <TableCell align='center' width={120}>
                                    {columnKey === 'actions' ? <div style={{background: 'white'}}
                                                                    className="flex items-center justify-around gap-2">
                                        <Tooltip content="Details">
                                          <span
                                              onClick={() => console.log('详情按钮', item.number)}
                                              className="text-lg text-default-400 cursor-pointer active:opacity-50"
                                          >
                                            <EyeIcon/>
                                          </span>
                                        </Tooltip>
                                        <Tooltip content="Edit food">
                                          <span
                                              className="text-lg text-default-400 cursor-pointer active:opacity-50"
                                              onClick={() => {
                                                  setCurrent(item)
                                                  setOpen(true)
                                                  console.log('formRef.current', formRef.current);
                                              }}
                                          >
                                            <EditIcon/>
                                          </span>
                                        </Tooltip>
                                        <Tooltip color="danger" content="Delete food">
                                          <span
                                              className="text-lg text-danger cursor-pointer active:opacity-50"
                                              // onClick={() => store.delFood(item)}
                                              onClick={() => {
                                                  fetch('/api3/users/delFood', {method: 'POST', data: {id: item.id}}).then((res) => {
                                                      console.log('删除回调', res);
                                                      if (res && res.errCode === 0){
                                                          messageApi.open({
                                                              type: 'success',
                                                              content: '删除成功',
                                                          });
                                                          store.getFoods();
                                                      }
                                                  })
                                              }}
                                          >
                                            <DeleteIcon/>
                                          </span>
                                        </Tooltip>
                                    </div> : getKeyValue(item, columnKey)}</TableCell>}
                        </TableRow>
                    )}
                </TableBody>
            </Table>
            <Modal
                isOpen={isOpen}
                placement="top-center"
                onOpenChange={(open) => {
                    if (!open) setCurrent({});
                    setOpen(open)
                }}
            >
                <ModalContent>
                    {(onClose) => (
                        <>
                            <ModalHeader className="flex flex-col gap-1">Edit</ModalHeader>
                            <FormA
                                style={{width: '100%'}}
                                validationBehavior="native"
                                onSubmit={onSubmit}
                                ref={formRef}
                            >
                                <ModalBody style={{width: '100%'}}>
                                    <Input
                                        isRequired
                                        label="名称"
                                        name='name'
                                        placeholder="请输入名称"
                                        variant="bordered"
                                        value={currentTarget.name}
                                        onChange={(e) => {
                                            console.log('ER',e);
                                            setCurrent({
                                                ...currentTarget,
                                                name: e.target.value
                                            })
                                        }}
                                    />
                                    <Input
                                        isRequired
                                        label="数量"
                                        name='number'
                                        placeholder="请输入数量"
                                        type="number"
                                        variant="bordered"
                                        value={currentTarget.number}
                                        onChange={(e) => {
                                            console.log('ER',e);
                                            setCurrent({
                                                ...currentTarget,
                                                number: e.target.value
                                            })
                                        }}
                                    />
                                    <Input
                                        isRequired
                                        label="价格"
                                        name='price'
                                        placeholder="请输入价格"
                                        type="number"
                                        variant="bordered"
                                        value={currentTarget.price}
                                        onChange={(e) => {
                                            console.log('ER',e);
                                            setCurrent({
                                                ...currentTarget,
                                                price: e.target.value
                                            })
                                        }}
                                    />
                                    <Input
                                        isRequired
                                        label="出发地"
                                        name='from'
                                        placeholder="请输入名称"
                                        variant="bordered"
                                        value={currentTarget.from}
                                        onChange={(e) => {
                                            console.log('ER',e);
                                            setCurrent({
                                                ...currentTarget,
                                                from: e.target.value
                                            })
                                        }}
                                    />
                                    <Input
                                        isRequired
                                        label="目的地"
                                        name='to'
                                        placeholder="请输入名称"
                                        variant="bordered"
                                        value={currentTarget.to}
                                        onChange={(e) => {
                                            console.log('ER',e);
                                            setCurrent({
                                                ...currentTarget,
                                                to: e.target.value
                                            })
                                        }}
                                    />
                                </ModalBody>
                                <ModalFooter style={{width: '100%'}}>
                                    <Button type="reset" color="danger" variant="flat" onPress={onClose}>
                                        Close
                                    </Button>
                                    <Button color="primary" type='submit'>
                                        Submit
                                    </Button>
                                </ModalFooter>
                            </FormA>
                        </>
                    )}
                </ModalContent>
            </Modal>
            <Modal
                isOpen={isAddModalOpen}
                placement="top-center"
                onOpenChange={(open) => {
                    if (!open) {
                        setNewItem({name: '', from: '', to: '', price: '', number: ''});
                    }
                    setAddModalOpen(open);
                }}
            >
                <ModalContent>
                    {(onClose) => (
                        <>
                            <ModalHeader className="flex flex-col gap-1">添加物品</ModalHeader>
                            <FormA
                                style={{width: '100%'}}
                                validationBehavior="native"
                                onSubmit={handleAddSubmit}
                            >
                                <ModalBody style={{width: '100%'}}>
                                    <Input
                                        isRequired
                                        label="名称"
                                        name="name"
                                        placeholder="请输入名称"
                                        variant="bordered"
                                        value={newItem.name}
                                        onChange={(e) => {
                                            setNewItem({
                                                ...newItem,
                                                name: e.target.value
                                            })
                                        }}
                                    />
                                    <Input
                                        isRequired
                                        label="数量"
                                        name="number"
                                        placeholder="请输入数量"
                                        type="number"
                                        variant="bordered"
                                        value={newItem.number}
                                        onChange={(e) => {
                                            setNewItem({
                                                ...newItem,
                                                number: e.target.value
                                            })
                                        }}
                                    />
                                    <Input
                                        isRequired
                                        label="价格"
                                        name="price"
                                        placeholder="请输入价格"
                                        type="number"
                                        variant="bordered"
                                        value={newItem.price}
                                        onChange={(e) => {
                                            setNewItem({
                                                ...newItem,
                                                price: e.target.value
                                            })
                                        }}
                                    />
                                    <Input
                                        isRequired
                                        label="出发地"
                                        name="from"
                                        placeholder="请输入出发地"
                                        variant="bordered"
                                        value={newItem.from}
                                        onChange={(e) => {
                                            setNewItem({
                                                ...newItem,
                                                from: e.target.value
                                            })
                                        }}
                                    />
                                    <Input
                                        isRequired
                                        label="目的地"
                                        name="to"
                                        placeholder="请输入目的地"
                                        variant="bordered"
                                        value={newItem.to}
                                        onChange={(e) => {
                                            setNewItem({
                                                ...newItem,
                                                to: e.target.value
                                            })
                                        }}
                                    />
                                </ModalBody>
                                <ModalFooter style={{width: '100%'}}>
                                    <Button type="reset" color="danger" variant="flat" onPress={onClose}>
                                        取消
                                    </Button>
                                    <Button color="primary" type="submit">
                                        确定
                                    </Button>
                                </ModalFooter>
                            </FormA>
                        </>
                    )}
                </ModalContent>
            </Modal>
        </div>
    );
});

export default Example;

// 使用 getStaticProps 来获取静态数据
export async function getStaticProps(props) {
    console.log('getStaticProps', props);
    return {
        props: {
            post: {
                name: 'post',
                // list: list
            },
        },
    };
}
